extends "res://scene/character/character_base.gd"

@onready var nav_agent: NavigationAgent2D = $NavigationAgent2D
@onready var anim: AnimatedSprite2D = $AnimatedSprite2D
@onready var attack_area: Area2D = $AttackArea

var enemy_in_range: bool = false

func _ready() -> void:
	self_group = "army"
	target_group = "enemy"
	max_health = 200
	attack_damage = 12.0
	attack_interval = 0.8
	tracking_radius = 300.0
	attack_area.area_entered.connect(_on_attack_area_entered)
	attack_area.area_exited.connect(_on_attack_area_exited)

func _physics_process(delta: float) -> void:
	# 更新攻击冷却计时器
	attack_timer = max(0.0, attack_timer - delta)
	
	# 更新追踪目标
	_update_target()
	if target == null:
		if anim:
			anim.play("idle")
		return
	
	# 敌人在范围内：停下并攻击
	if enemy_in_range:
		velocity = Vector2.ZERO
		# 防止导航代理引起位置跳变
		if nav_agent:
			nav_agent.target_position = global_position
		
		# 处理攻击动画和朝向
		if attack_timer <= 0.0:
			attack()
			if anim:
				anim.flip_h = (target.global_position.x - global_position.x) < 0
				if anim.animation != "attack_right":
					anim.play("attack_right")
		
		move_and_slide()
		return
	
	# 执行移动逻辑
	var was_moving = velocity.length() > 0
	_move_to_target()
	
	# 处理移动动画
	if anim:
		var is_moving = velocity.length() > 0
		if is_moving:
			# 根据移动方向翻转精灵
			if velocity.x > 0:
				anim.flip_h = false  # 向右移动，不翻转
			elif velocity.x < 0:
				anim.flip_h = true   # 向左移动，翻转
			# 播放跑步动画
			anim.play("run_right")
		elif not was_moving:
			# 停止时播放待机动画
			anim.play("idle")
	
	move_and_slide()

func attack() -> void:
	if attack_timer > 0.0 or not target or not is_instance_valid(target):
		return
	super.attack()
	_do_attack(target)

func _do_attack(t: Node2D) -> void:
	if t == null or not is_instance_valid(t):
		return	
	if t.has_method("get_damage"):
		t.get_damage(attack_damage, self)
		print("士兵造成" + str(attack_damage) + "点伤害")

func _on_attack_area_entered(area: Area2D) -> void:
	# 只有在碰到当前目标的 HurtArea 时才进入攻击范围
	if not target:
		return
	var parent := area.get_parent()
	if parent == target:
		enemy_in_range = true

func _on_attack_area_exited(area: Area2D) -> void:
	# 退出时若与当前目标相关，则离开攻击范围
	if not target:
		return
	var parent := area.get_parent()
	if parent == target:
		enemy_in_range = false
